<template>
  <div class="app-container">
    <el-card class="box-card" shadow="never" style="border:0px;" v-loading="loading">
      <div slot="header" style="font-size:14px;font-weight:bold;">
        <span>待进件管理</span>
      </div>
        <!-- 查询和其他操作 -->
      <div class="filter-container" id="searchBox">
        <div class="left">
        <el-form :inline="true" ref="listQuery" :model="listQuery" class="demo-form-inline" size="medium" label-position="right">
          <el-form-item label="姓名/手机号：" prop="realNameOrMobile">
            <el-input v-model="listQuery.realNameOrMobile" clearable class="filter-item" placeholder="请输入借款人姓名/手机号"/>
                  </el-form-item>
          <el-form-item label="身份证：" prop="idCardNo">
               <el-input v-model="listQuery.idCardNo" clearable class="filter-item" placeholder="请输入借款人身份证"/>
          </el-form-item>
          <el-form-item label="创建时间：" prop="projectCreateDateArr">
            <el-date-picker
              class="date_item"
              v-model="listQuery.projectCreateDateArr"
              type="daterange"
              range-separator="至"
              align="right"
              value-format="yyyy-MM-dd"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="贷款类型" prop="loanType">
            <el-select v-model="listQuery.loanType" placeholder="请选择" style="min-width:100%;" @change="getList">
              <el-option
                v-for="item in loanTypes"
                :key="item.dictValue"
                :label="item.dictName"
                :value="item.dictValue">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        </div>
        <div class="right">
             <el-button  type="primary" @click="handleFilter">查询</el-button>
             <el-button  @click="restForm('listQuery')">重置</el-button>
        </div>
      </div>

    <vxe-toolbar ref="xToolbar">
         <template #buttons>
           <el-dropdown trigger="click" style="margin-right:10px;" @command="handleCommand">
            <span class="el-dropdown-link">
              提交进件<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item icon="el-icon-circle-plus-outline" command="房抵贷">房抵贷</el-dropdown-item>
              <el-dropdown-item icon="el-icon-circle-plus" command="信用贷" v-permission="'system:credit-loan-submit-project:access'">信用贷</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
         <el-button v-permission="'system:project-list-menu:ev'"  v-loading="loading" type="text" icon="el-icon-thumb" @click="evHouseEvent">房产评估</el-button>
         <el-button v-permission="'*'"  v-loading="loading" type="text" icon="el-icon-bicycle" @click="taskRefer">数据迁移</el-button>
        </template>
    </vxe-toolbar>
    <vxe-table
      v-loading="loading"
      :data="data"
      border="none"
      highlight-hover-row
      show-header-overflow
      show-overflow
      align="center"
      :header-cell-style="{background:'#F7F7F8',color:'#606266'}"
        @cell-dblclick="cellDblclick"
      >
      <vxe-table-column type="seq" title="序号" min-width="60"/>
      <vxe-table-column title="借款人" field="realName"  min-width="150"/>
      <vxe-table-column title="证件号码" field="idCardNo" min-width="180" />
      <vxe-table-column title="手机号" field="mobile"  min-width="130"/>
      <vxe-table-column title="资方" field="capitalName" min-width="100"/>
      <vxe-table-column title="产品名称" field="productName" min-width="140"/>
      <vxe-table-column title="贷款类型" field="loanType" min-width="100">
        <template v-slot="{row}">{{row.loanType==1 ? "房抵贷" : "信用贷"}}</template>
      </vxe-table-column>
      <vxe-table-column title="贷款金额(万)" field="applyAmount" min-width="140">
        <template v-slot="{row}">{{row.applyAmount}}</template>
      </vxe-table-column>
      <vxe-table-column title="创建时间" field="createTime" min-width="180"/>
      <vxe-table-column title="客户经理" field="creatorName" min-width="150"/>
      <vxe-table-column title="项目状态" field="projectStatusName" min-width="150"/>
      <vxe-table-column title="操作" align="center" fixed="right" min-width="280">
        <template v-slot="{ row }">
          <span v-if="row.loanType === 1">
            <el-button type="text" @click="startTask(row)" v-if="row.projectStatus === 3" v-loading="loading">提交项目</el-button>
            <el-divider v-if="row.projectStatus === 3" direction="vertical"></el-divider>
          </span>
          <span v-if="row.loanType === 2">
            <el-button type="text" @click="creditStartTask(row)" v-if="row.projectStatus === 0" v-loading="loading">提交项目</el-button>
            <el-divider v-if="row.projectStatus === 0" direction="vertical"></el-divider>
          </span>
          <el-button type="text" v-if="handelEditChoose(row)" @click="editUser(row)">编辑</el-button>
          <el-button type="text" v-else  @click="lookDetail(row)">查看</el-button>
          <el-divider v-if="handelDeleteChoose(row)" direction="vertical"></el-divider>
          <el-button type="text" v-if="handelDeleteChoose(row)"  @click="deleteByProjectId(row)">删除</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-button type="text" @click="setVisbile(row)">归属转移</el-button>
        </template>
      </vxe-table-column>
    </vxe-table>

 </el-card>

    <vxe-pager
      class="pager"
      @page-change="changePage"
      :current-page.sync="listQuery.pageNo"
      :page-size.sync="listQuery.pageSize"
      :total="total"
      :page-sizes="[10, 30, 50,100]"
      :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
    >
    </vxe-pager>
    <transfer :dialogVisible="dialogVisible" :row="projectRow" @close="transferClose" :projectId="projectId" @getList="getList"/>
  </div>
</template>

<script>
  import { waitList, startTask, deleteByProjectId, secondSubmit, listTasks } from '@/api/project'
import { creditStartTask,taskRefer } from '@/api/creditLoan'
import DicSelect from '@/components/select'
import Transfer from '@/components/transfer'
import { mapGetters } from 'vuex'
import {getProcessKey} from '@/utils/index'
  import { findByDictTypeName } from '@/api/dict'
export default {
  name: 'Index',
  components: { DicSelect,Transfer },
  data() {
    return {
      active: 0,
      data: [],
      total: 0,
      isCustomerManager: false,
      listQuery: {
        pageNo: 1,
        pageSize: 10,
        realNameOrMobile: undefined,
        idCardNo: undefined,
        pledgeType: undefined,
        submitStartDate: undefined,
        submitEndDate: undefined,
        loanType: undefined,
        projectCreateDateArr: undefined,
      },
      loanTypes:undefined,
      showAll:true,
      loading: true,
      dialogVisible:false,
      projectRow:{
        realName:undefined,
        idCardNo:undefined,
        transferObj:undefined
      },
      projectId:undefined
    };
  },
  computed: {
    ...mapGetters(['roles','processKey']),
    showOperation: function() {
   if (this.showAll == false) {
    //对文字进行处理
    return "展开";
   } else {
    return "收起";
   }
  }
  },
  mounted(){
  /**
   * 收起搜索
   */
  this.$nextTick(function() {
  //  this.closeSearch();
  });
  },
  created() {
    localStorage.removeItem("projectIdByDraw")
    localStorage.removeItem("borrowerId")
    localStorage.removeItem("projectId")
    localStorage.removeItem("backIdCardNo")
    this.getList();
    if( this.roles.indexOf("客户经理")!=-1){
        this.isCustomerManager = true
    }
    this.findByDictTypeName('项目贷款类型');
  },
  methods: {
    closeSearch() {
     this.showAll = !this.showAll;
     var searchBoxHeght = document.getElementById("searchBox");
     if (this.showAll == false) {
      searchBoxHeght.style.height = 50 + "px";
     } else {
      searchBoxHeght.style.height = "auto";
     }
    },
    findByDictTypeName(dictTypeName) {
      findByDictTypeName(dictTypeName).then((data) => {
        this.loanTypes = data.data;
      });
    },
    restForm(formName){
      this.$refs[formName].resetFields();
      this.listQuery.projectCreateDateArr = undefined;
      this.getList()
    },
    getList() {
      this.loading = true;
      waitList(this.listQuery).then((data) => {
          this.data = data.data;
          this.total = data.total;
          this.loading = false;
        }).catch((error) => {
          console.error('请求用户数据发生异常:' + error);
          this.loading = false;
        });
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    handelDeleteChoose(row){
      if( row.projectStatus === 3|| row.projectStatus === 0 ){
        // if( (row.projectStatus === 102 || row.projectStatus === 104) && this.isCustomerManager){
        //   return false
        // }
        return true
      }
    },
    handelEditChoose(row){
      if( row.projectStatus === 3  || row.projectStatus === 0 ){
        // if( (row.projectStatus === 102 || row.projectStatus === 104) && this.isCustomerManager){
        //   return false row.projectStatus === 102 || row.projectStatus === 104 ||
        // }
        return true
      }
    },
    deleteByProjectId(row) {
       this.$confirm('确定要删除此笔项目吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
           deleteByProjectId(row.id)
            .then((data) => {
              this.$notify.success("删除成功")
              this.getList()
            })
            .catch((err) => {
              console.error('删除失败');
            });
        }).catch(() => {
           this.$message("已取消删除")
        });
     },
    updateUserById(row) {
      this.$XModal.confirm(`确定更新吗${row.name}吗`).then((type) => {
        if (type === 'confirm') {
        }
      });
    },
    resetEvent() {
      this.getList();
    },
    changePage() {
      this.getList();
    },

    startTask(row) {
      this.$confirm('确定提交此笔进件项目吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true;
          startTask(row.id)
              .then((data) => {
              this.$notify({title: '成功',message: '提交成功',type: 'success'});
              this.getList()
              this.loading = false;
            }) .catch(() => {
            this.loading = false;
          })
        }).catch(() => {
            this.loading = false;
           this.$message("已取消提交")
        });
    },
    // 信用贷项目提交
    creditStartTask(row) {
      this.$confirm('确定提交此笔进件项目吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true;
        creditStartTask(row.id,row.orgId)
              .then((data) => {
              this.$notify({title: '成功',message: '提交成功',type: 'success'});
              this.getList()
              this.loading = false;
            }) .catch(() => {
            this.loading = false;
          })
        }).catch(() => {
            this.loading = false;
           this.$message("已取消提交")
        });
    },

    secondSubmit(row) {
      this.$router.push({ path: '/detail/deal' , query: { projectId: row.id,projectStatus: row.projectStatus }})
    },
    editUser(row) {
      // let processKey = row.processKey
      let processKey = getProcessKey(row.processKey)
      //首先判断是否是信用贷项目
      if(row.loanType == 2) {
        this.$router.push({path:"/project/addCredit",query:{projectId: row.id}})
        return false
      }

      //是否是草稿状态
      if(row.projectStatus === 0 ) {
        if(processKey == "dg") {
          this.$router.push({path:"/project/add_dg",query:{ idCardNo: row.idCardNo,projectIdByDraw: row.id,operation: 'edit'}})
        }else{
        this.$router.push({path:"/project/add",query:{ idCardNo: row.idCardNo,projectIdByDraw: row.id,operation: 'edit'}})
        }

      }else{
         //跳转到编辑页面
         if(processKey == "dg") {
          this.$router.push({ path: '/project/edit_dg' , query: { projectId: row.id }})
        }else{
          this.$router.push({ path: '/project/edit' , query: { projectId: row.id }})
        }

      }
    },
    lookDetail(row) {
      if (row.loanType === 1){
        //跳转到审批页面
        // let processKey = row.processKey
        let processKey = getProcessKey(row.processKey)
        if(processKey == "dg") {
          this.$router.push({ path: '/detail/deal_dg' , query: { projectId: row.id,projectStatus: row.projectStatus,operationLook: true,activeIndex: "1" }})
        }else{
          this.$router.push({ path: '/detail/deal' , query: { projectId: row.id,projectStatus: row.projectStatus,operationLook: true,activeIndex: "1" }})
        }
      }
      if (row.loanType === 2){
        // 跳转到信用贷审批页面
        console.log(row)
        this.$router.push({ path: '/task/deal_credit' ,
          query: { projectId: row.projectId, taskId: row.id, projectStatus: row.projectStatus,taskStatus: row.taskStatus,realName:row.realName,isNeedSubmit:false},
        })
      }
    },
    addUserEvent() {
      console.log(this.processKey)
      // let processKey = this.processKey
      let processKey = getProcessKey(this.processKey)
      if(processKey == "dg") {
         this.$router.push({ path: '/project/add_dg',query: {operation: 'add'} })
      }else{
        this.$router.push({ path: '/project/add',query: {operation: 'add'} })
      }
    },
    handleCommand(command) {
      if(command === "房抵贷"){
        this.addUserEvent()
      }else{
        this.$router.push({ path: '/project/addCredit',query: {operation: 'add'} })
      }

    },

    taskRefer() {
      this.loading = true;
      taskRefer().then((data) => {
        console.log('响应数据:%o', data);
        this.loading = false;
        this.$notify.success({title: '成功',message: '迁移成功',});
      }).catch(() => {
        this.$message("迁移失败")
      });
    },

    evHouseEvent() {
      this.$router.push({ path: '/project/ev' })
    },
    closeModal() {
      this.modalUpdate.row = {};
      this.modalUpdate.originRow = {};
    },
    cellDblclick({row,rowIndex,column,columnIndex,cell},event) {
      let _this = this;
      this.$copyText(event.target.innerText).then(function() {
        _this.$message.info('复制成功');
      });
    },
    setVisbile(row) {
      this.dialogVisible = true
      this.projectId = row.id
      this.projectRow = {
        realName:row.realName,
        idCardNo: row.idCardNo,
        transferObj:undefined
      }
    },
    transferClose() {
      this.dialogVisible =false
    }
  },
};
</script>

<style lang="css" scoped>
.filter-container{
  display: flex;
  justify-content: space-between;

}
#searchBox {
 overflow: hidden;
}

.pager{
  position: fixed;
  bottom: 0;
  right: 28px;
  background-color: #FAFAFB;
  z-index: 2;
  height: 40px;
  width: calc(100% - 260px);
  }

.right >>> .el-button--primary,.el-button--default {
  padding: 10px 20px;
}

.vxe-table--render-default >>> .el-button--text{
  color: #2b7bfb;
}
.app-container >>> .vxe-table--render-default,.vxe-pager {
  font-family: PingFangSC, Arial, Helvetica, sans-serif;
}


.left {
    flex: 14;
    display: flex;
    flex-flow: row wrap;
    margin-right: 20px;


}
.left >>> .el-form{
      width: 100%;
}
.left >>> .el-form .el-form-item {
        display: flex;
        flex-flow: row nowrap;
        width: 30%;
        margin-right: 3%;
        float: left;
        margin-bottom: 14px;
}


.left >>> .el-form .el-form-item .el-form-item__label{
    font-weight: 500;
    color: #606266;
    text-align: left;
     /* flex: 1; */
}

.left >>> .el-form .el-form-item .el-form-item__content {
          flex: 1;
          /*超出部分隐藏*/
          text-overflow: ellipsis;
          /* 超出部分显示省略号 */
          white-space: nowrap;
          /*规定段落中的文本不进行换行 */
          width: 100%;
        }
 .date_item {
   width: 100%;
 }
 .right {
    flex: 2;
    display: flex;
    flex-flow: row nowrap;
    align-items: flex-end;
    margin-right: 30px;
    /* margin-bottom: 30px; */
 }
  .el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
  }
  .el-icon-arrow-down {
    font-size: 12px;
  }
  .demonstration {
    display: block;
    color: #8492a6;
    font-size: 14px;
    margin-bottom: 20px;
  }
</style>
